
import { BasePlatform } from "../../framework/base/BasePlatform";
import { TimeUtils } from "../../framework/utils/TimeUtils";


export class BytedancePlatform implements BasePlatform {
    nativeCode?: string;
    //激励视频
    private videoAd = null;
    //banner
    private BannerAd = null;
    //插屏
    private InterstitialAd = null;

    //banner高度
    private BannerAdHight: number = 0
    //banner宽度
    private BannerAdWight: number = 0
    //插屏广告间隔
    private showInsertTime = 0;
    //系统信息
    private systemInfo
    //是否登录
    private isLogin: boolean = false;
    /**录屏路径 */
    private videpPath: string = null


    initSdk(args?: any, callback?: Function) {
        let self = this
        tt.login({
            force: false,
            success(res) {
                self.isLogin = res.isLogin;
                console.log(`login 调用成功${res.code} ${res.anonymousCode}`);
            },
            fail(res) {
                self.isLogin = false;
                console.log(`login 调用失败`);
            },
        });
        // 调用此方法上报anonymousOpenid
        this.systemInfo = tt.getSystemInfoSync();
        const windowWidth = this.systemInfo.windowWidth
        const windowHeight = this.systemInfo.windowHeight


        this.videoAd = tt.createRewardedVideoAd({ adUnitId: "31r5stfqj0enh8i373" })

        // this.BannerAd = tt.createBannerAd({
        //     adUnitId: '9r0a8l75sdr5vct0qq',
        //     style: {
        //         left: (windowWidth - 300) / 2,
        //         top: 0,
        //         adIntervals: 30,
        //         width: 300,
        //     }
        // })

        // // 尺寸调整时会触发回调，通过回调拿到的广告真实宽高再进行定位适配处理
        // // 注意：如果在回调里再次调整尺寸，要确保不要触发死循环！！！
        // this.BannerAd.onResize((size) => {
        //     //console.log(" 尺寸调整时会触发回调==============>") 
        //     // good
        //     console.log(size.width, size.height);
        //     this.BannerAdHight = size.height
        //     this.BannerAdWight = size.width
        //     this.BannerAd.style.top = windowHeight - this.BannerAdHight
        //     this.BannerAd.style.left = (windowWidth - this.BannerAdWight) / 2
        // });

        // this.BannerAd.onError((err) => {
        //     console.log(' banner 广告错误', err.errCode);
        // })





    }
    /**
     * 分享视频
     * @param args 
     * @param callback 
     * @returns 
     */
    shareVideo?(args?: any, callback?: Function) {
        let videopath = this.videpPath
        let self = this
        if (videopath == null || videopath.length == 0 || videopath == undefined) {
            tt.showToast({
                title: "还没有分享内容",
                duration: 2000,
                success(res) { },
                fail(res) { },
            });
            return
        }
        // 视频分享
        tt.shareAppMessage({
            channel: "video",
            query: "",
            templateId: "2h0m2rn4sa8dl549h5", // 替换成通过审核的分享ID
            title: "理科生你来呀",
            desc: "理科生你来呀",
            extra: {
                videoPath: videopath, // 可用录屏得到的本地文件路径
                videoTopics: ["理科生你来呀"],
                withVideoId: true,
            },
            success() {
                self.videpPath = null
                //  console.log("分享视频成功");
                tt.showToast({
                    title: "分享视频成功",
                    duration: 2000,
                    success(res) { },
                    fail(res) { },
                });
                if (callback) {
                    callback()
                }
            },
            fail(e) {
                // console.log("-------分享视频失败---------------", e)
                tt.showToast({
                    title: "分享视频失败",
                    duration: 2000, success(res) { },
                    fail(res) { },
                });
            },
        });
    }

    /**
     * 分享图片
     * @param args 
     * @param callback 
     */
    shareImg(args: any, callback: Function) {
        let pre = "https://game2.sfplay.net/werid_assets/wechat/shareIcon/"
        let imgUrl = ["1.jpeg", "2.jpeg", "3.jpeg"]
        let titleArr = ["帮我看看哪个字错了？", "你是逃不过我的眼睛的！", "帮我看看哪一只不是企鹅"];
        let ind = Math.floor(Math.random() * 3);
        tt.shareAppMessage({
            title: titleArr[ind],
            desc: "",
            imageUrl: pre + imgUrl[ind],
            query: "",
            success() {
                if (callback) {
                    callback()
                }
                console.log("分享成功");
            },
            fail(e) {
                console.log("分享失败");
            },
        });
    }

    /**
     * 是否添加桌面
     * @param args 
     * @param callback true已添加 false未添加 
     */
    checkShortcut(args?: any, callback?: Function) {
        tt.checkShortcut({
            success: function (res) {
                if (res.status.exist) {
                    if (callback) {
                        callback(true)
                    }
                } else {
                    if (callback) {
                        callback(false)
                    }
                }
            },
            fail: function (res) {
                if (callback) {
                    callback(true)
                }
            }
        })
    }

    /**
     * 添加到桌面
     * @param args 
     * @param callback 
     */
    addShortcut(args?: any, callback?: Function) {
        tt.addShortcut({
            success: function (res) {
                if (callback) {
                    callback("桌面图标添加成功")
                }
            },
            fail: function (res) {
                if (callback) {
                    callback("桌面图标添加失败")
                }
            }
        })
    }

    hasVerify() {
        return false
    }






    /**获取用户的名字和头像 必须回传 没有返回null */
    getUserInfo(callback: Function) {
        tt.login({
            force: false,
            success(res) {
                console.log("登录成功");
                // 调用 getUserInfo 前, 请确保登录成功
                // 获取用户信息
                tt.getUserInfo({
                    // withCredentials: true,
                    // withRealNameAuthenticationInfo: true,
                    success(res) {
                        if (res.errMsg == "getUserInfo:ok") {
                            callback(res.userInfo.nickName, res.userInfo.avatarUrl)
                        } else {
                            callback(null, null)
                        }
                    },
                    fail(res) {
                        callback(null, null)
                    },
                });
            },
        });
    }


    /**
     * 更多游戏
     * @param args 
     * @param callback 
     */
    showGamePortalAd(args?: any, callback?: Function) {
        // 监听弹窗关闭
        tt.onMoreGamesModalClose(function (res) {
        });
        // 监听小游戏盒子跳转
        tt.onNavigateToMiniGameBox(function (res) {
        });

        if (this.systemInfo.platform !== "ios" && tt.showMoreGamesModal) { // iOS 不支持，建议先检测再使用
            // 打开小游戏盒子
            tt.showMoreGamesModal({
                appLaunchOptions: [
                    { appId: "ttd63da0804905658f02", },
                    { appId: "tt3b934d2ea4ab8a8202", },
                    { appId: "tta7dcd16138e7e202" },
                    { appId: "tt9325e5980c1e8576" },
                    { appId: "ttf1bf87026e84c9f9" },
                    { appId: "tt93c9e5740cf268b9" },
                    { appId: "ttf21484a96d2f6816" },
                    { appId: "tt6a4c1cf1f5761949" },
                    { appId: "tt0c7a7ac793413665" },
                    { appId: "tt914ae7f70e72364302" }
                ],
                success(res) {
                },
                fail(res) {
                    if (callback) {
                        callback("error")
                    }
                },
            });
        } else {
            if (callback) {
                callback(null)
            }
        }
    }



    trackAppKey: string;
    canShare(): boolean {
        return true
    }
    pauseRecord() {
        const recorder = tt.getGameRecorderManager();
        recorder.pause();
    }
    resumeRecord() {
        const recorder = tt.getGameRecorderManager();
        recorder.resume();
    }

    youmengTrack(key?: string, groupID?: string, groupValue?: string) {
        if (!tt.uma) {
            return
        }
        if (groupID && groupValue) {
            if (groupID == "userA") {
                tt.uma.trackEvent(key, { "userA": groupValue });
            } else if (groupID == "userB") {
                tt.uma.trackEvent(key, { "userB": groupValue });
            } else if (groupID == "userD") {
                tt.uma.trackEvent(key, { "userD": groupValue });
            } else {
                tt.uma.trackEvent(key, { "userC": groupValue });
            }
        } else {
            tt.uma.trackEvent(key); // 友盟统计
        }
    }
    hasShare: boolean;

    recordVideo(args?: any, callback?: Function) {
        const recorder = tt.getGameRecorderManager();
        if (!recorder) {
            return;
        }
        this.videpPath = null;
        recorder.onStart((res) => {
            console.log("录屏开始");
            // do somethine;
        });
        //添加水印并且居中处理
        recorder.start({
            duration: 300,
            isMarkOpen: false,
        });

    }



    showVideoAd(args?: any, callback?: Function, error?: Function, stub?: string) {
        this.videoAd.show().then(() => {
            //console.log("广告显示成功===>",platform);
        }).catch((err) => {
            console.log("广告组件出现问题", err);
            // 可以手动加载一次
            this.videoAd.load().then(() => {
                console.log("手动加载成功");
                // 加载成功后需要再显示广告
                return this.videoAd.show();
            });
        });
        var that = this
        let closefunc = (res) => {
            if (res && res.isEnded) {
                if (callback) {
                    // that.youmengTrack("videosuccess")
                    callback()
                }
                // console.log("正常播放结束，可以下发游戏奖励");
            } else {
                error()
                //console.log("播放中途退出，不下发游戏奖励");
            }
            that.videoAd.offClose(closefunc)
            that.videoAd.load()

        }
        this.videoAd.onClose(closefunc)


        this.videoAd.onError((errCode, errMsg) => {
            let tips: string = '暂无广告';
            if (errMsg && errMsg.length > 0) {
                error(errMsg)
            } else {
                error(tips)
            }
        })
    }



    setLanguage(args?: any, callback?: Function): string {
        return ""
    }

    stopRecorderManager(args?: any, callback?: Function) {
        const recorder = tt.getGameRecorderManager();
        recorder.onStop((res) => {
            this.videpPath = res.videoPath;
            if (callback) {
                callback(res.videoPath)
            }
        });
        recorder.stop();
    }

    getAppName(args?: any, callback?: Function) {
        const appName = this.systemInfo.appName;
        return appName;
    }

    private isLoginByte = false;
    private loginState = false;
    login(args?: any, callback?: Function) {
        if (!this.isLoginByte) {
            let that = this;
            tt.login({
                force: false,
                success(res) {
                    // 调用 getUserInfo 前, 请确保登录成功
                    // 获取用户信息
                    that.isLoginByte = true;
                    that.loginState = res.isLogin
                    callback(res.isLogin);

                },
            });
        } else {
            callback(this.loginState)
        }


    }
    pay(args?: any, callback?: Function) {
    }

    showBanner(args?: any, callback?: Function) {
        if (this.BannerAd == null || this.systemInfo.appName === "XiGua") {
            return
        }
        this.BannerAd.show()
    }
    hideBanner(args?: any, callback?: Function) {
        if (this.BannerAd != null || this.systemInfo.appName === "XiGua") {
            this.BannerAd.hide()
        }
    }
    showInsertAd(args?: any, callback?: Function) {
        var nowTime = TimeUtils.GetTimeBySecond();
        if (nowTime - this.showInsertTime >= 31) {
            // 只有头条支持插屏广告
            const appName = this.systemInfo.appName;
            if (appName == 'Toutiao' || appName == 'Douyin') {
                if (this.InterstitialAd) {
                    this.InterstitialAd.destroy();
                    this.InterstitialAd = null;
                }
                this.InterstitialAd = tt.createInterstitialAd({
                    adUnitId: "46pmmakp45o1g0jg0g",
                });

                this.InterstitialAd.load().then(() => {
                    this.InterstitialAd.show().then(() => {
                        this.showInsertTime = TimeUtils.GetTimeBySecond();
                        if (callback) callback()
                    }).catch(err => {
                        //展示插屏广告失败
                        if (callback) callback()
                    });
                }).
                    catch(err => {
                        //加载插屏广告失败
                        if (callback) callback()
                    });
            }
        }
    }


    canCare(): boolean {
        if (this.systemInfo.appName == "Douyin") {
            return true;
        }
        return false
    }
    otherFun(args?: any, callback?: Function) {
        //抖音关注
        if (this.systemInfo.appName == "Douyin") {
            tt.login({
                force: false,
                success(res) {
                    console.log("登录成功");
                    // 调用 getUserInfo 前, 请确保登录成功
                    // 获取用户信息
                    if (res.isLogin) {
                        if (tt.openAwemeUserProfile) {
                            tt.openAwemeUserProfile();
                            setTimeout(() => {
                                if (callback) {
                                    callback()
                                }
                            }, 3500)
                        } else {
                            tt.showToast({
                                title: "暂不支持该功能",
                                duration: 2000,
                                success(res) { },
                                fail(res) { },
                            });
                        }
                    } else {
                        tt.showToast({
                            title: "请先登录",
                            duration: 2000,
                            success(res) { },
                            fail(res) { },
                        });
                    }

                },
            });

        } else {
            tt.showToast({
                title: "暂不支持该功能",
                duration: 2000,
                success(res) { },
                fail(res) { },
            });
        }

    }
    /**点击home*/
    homeToBackgroud(args?: any, callback?: Function) {

    }
    /**回到界面*/
    backgroudToHome(args?: any, callback?: Function) {

    }
    openNotify() { }
    registerNotify(key: string, second: number, content: string) { }
    deleteNotify(key: string) { }

    shark(args?: any, callback?: Function) {
        args == 1 ? tt.vibrateLong() : tt.vibrateShort()

    }
    /**分享 */
    openShare(args?: any, callback?: Function) { }

    compareVersion(v1, v2) {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)

        while (v1.length < len) {
            v1.push('0')
        }
        while (v2.length < len) {
            v2.push('0')
        }

        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i])
            const num2 = parseInt(v2[i])

            if (num1 > num2) {
                return 1
            } else if (num1 < num2) {
                return -1
            }
        }

        return 0
    }


    share(args?: any, callback?: Function) {

    }
    getCode?(callback?: Function): string {
        return "134"
    }
    verifyKey?(str: string) {

    }
    toAppStore?(callback?: Function) {

    }

    addCollect(callback?: Function) {
        tt.showFavoriteGuide({
            type: "customize",
            success(res) {
                if (callback) {
                    callback(res.isFavorited)
                }
                // console.log("isFavorited", res.isFavorited);  //此处输出 “ifFavorited：true” 代表用户已收藏，若为false代表用户未收藏
            },
            fail(res) {
                // console.log("自定义弹窗展示失败");
                if (callback) {
                    callback(false)
                }
            },
        });
    }

    addDesktop(callback?: Function) {
        // tt.checkShortcut({
        //     success(res) {
        //         if (callback) {
        //             callback(false);
        //         }
        //     },
        //     fail(res) {
        tt.addShortcut({
            success() {
                // console.log("添加桌面成功")s;
                if (callback) {
                    callback(true);
                }
            },
            fail(err) {
                // console.log("添加桌面失败", err.errMsg);
                if (callback) {
                    callback(false, err.errMsg);
                }
            },
        });
        //     },
        // });
    }

    //检测是否支持跳转侧边栏
    checkSideBar(callback?: Function) {
        tt.checkScene({
            scene: "sidebar",
            success: (res) => {
                console.log("check scene success: ", res.isExist);
                //成功回调逻辑
                if (callback) {
                    callback(res.isExist);
                }
            },
            fail: (res) => {
                console.log("check scene fail:", res);
                //失败回调逻辑
                if (callback) {
                    callback(false);
                }
            }
        });
    }

    receptionListen(callback?: Function) {
        tt.onshow((res) => {
            if (callback) {
                callback(res);
            }
        });
    }

    jumpSidebar(callback?: Function) {
        tt.navigateToScene({
            scene: "sidebar",
            success: (res) => {
                console.log("navigate to scene success");
                // 跳转成功回调逻辑
            },
            fail: (res) => {
                console.log("navigate to scene fail: ", res);
                // 跳转失败回调逻辑
            },
        });
    }

    reportEvent(eventId: string, data: object) {
        tt.reportAnalytics(eventId, data);
    }

}
